package com.example.exam.filter;

import com.example.exam.pojo.ManagementUser;
import com.example.exam.service.ManagementUserService;
import com.example.exam.utils.JsonUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * @date 2023/03/15
 *
 * 管理员过滤器
 */
public class ManagementFilter implements HandlerInterceptor {

    private ManagementUserService userService;

    public ManagementFilter(ManagementUserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取令牌
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if(token == null) {
            output(response, 2001, "未登录");
            return false;
        }
        String[] strings = new String(Base64.getDecoder().decode(token.getBytes())).split(":");
        ManagementUser user = userService.searchAllByUsername(strings[0]);
        if(user == null) {
            output(response, 2002, "登录已过期");
            return false;
        }
        return true;
    }

    private void output(HttpServletResponse response, int code, String msg) throws IOException {
        Map<String, Object> map = new HashMap<>(2);
        //错误状态码
        map.put("code", code);
        //错误信息
        map.put("msg", msg);
        String json = JsonUtil.toString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(json);
    }
}
